import PageLoading from "./PageLoading";
import ReactDOM from "react-dom";
import { ReactElement } from "react";

class CreateLoading {
  elements: ReactElement;
  wrapper: Element;
  isLoading: boolean;
  delay: number;

  constructor() {
    this._init();
  }

  private _init() {
    this.isLoading = false;
    this.delay = 300;
    this.elements = PageLoading();
    this.wrapper = this._createWrapper();
  }

  private _createWrapper(): Element {
    const wrapper = document.createElement("div");
    wrapper.className = "wrapper-loading";
    return wrapper;
  }
  private _dispose() {
    if (this.wrapper) document.body.removeChild(this.wrapper);
  }

  private _toggleAcitve(state: boolean) {
    this.wrapper.classList.toggle("active", state);
  }
  public showLoading() {
    if (this.isLoading) return;
    const { elements, wrapper } = this;

    this.isLoading = true;
    ReactDOM.render(elements, wrapper);
    document.body.appendChild(wrapper);
    setTimeout(() => this._toggleAcitve(true), 0);
  }
  public hideLoading(notUseAnimation?) {
    if (!this.isLoading) return;

    this._toggleAcitve(false);
    this.isLoading = false;
    setTimeout(this._dispose.bind(this), notUseAnimation ? 0 : this.delay);
  }
}

export default new CreateLoading();
